<?php
/**
 * 框架应用生成类
 * @copyright Copyright(c) 2020 WillPHP
 * @author DaSongzi <24203741@qq.com/113344.com>
 * @version 2.0
 * @since 2020-09-08
 */
namespace wiphp;
final class Build {
	public static function app() {	
		$lock = WPHP_URI.'/app/build.lock';
		if (!is_writable($lock)) {
			if (!touch($lock)) {
				exit('应用目录和缓存目录不可写，目录无法自动生成！请手动生成目录！');
			}
			if (!file_exists(WPHP_URI.'/app/common.php')) {
				file_put_contents(WPHP_URI.'/app/common.php', "<?php\n//自定义函数放这里");
			}
			if (!is_dir(APP_PATH)) mkdir(APP_PATH, 0755, true);
			if (!is_dir(PATH_RUNTIME)) mkdir(PATH_RUNTIME, 0755, true);
			$dirs = array();
			$dirs[] = APP_PATH.'/config';
			$dirs[] = APP_PATH.'/controller';
			$dirs[] = APP_PATH.'/model';
			$dirs[] = APP_PATH.'/widget';
			$dirs[] = APP_PATH.'/validate';
			$dirs[] = PATH_VIEW;
			$dirs[] = APP_PATH.'/view/index';
			$dirs[] = APP_PATH.'/view/public';
			$dirs[] = PATH_CACHE;
			$dirs[] = PATH_LOG;
			$dirs[] = PATH_VIEWC;
            $dirs[] = PATH_SHTML;
			foreach ($dirs as $dir) {
				if(!is_dir($dir)) mkdir($dir, 0755, true);
			}
			//首页模板
			$v_index = file_get_contents(WPHP_PATH.'/wihtml/welcome.html');
			file_put_contents(APP_PATH.'/view/Index/index.html', $v_index);
			//转跳模板
			$v_tips = file_get_contents(WPHP_PATH.'/wihtml/jump.html');
			file_put_contents(APP_PATH.'/view/Public/jump.html', $v_tips);
			//默认控制器
			$p_index = "<?php\nnamespace home\\controller;\nclass IndexController{\n\tpublic function index(){\n\t\treturn view();\n\t}\n\tpublic function view(\$id){\n\t\treturn 'view/'.\$id.' 路由访问  Index/view/id/'.\$id;\n\t}\n}";
			file_put_contents(APP_PATH.'/controller/IndexController.php', $p_index);
			//空控制器和空操作
			$p_empty = "<?php\nnamespace home\\controller;\nclass EmptyController{\n\tuse \\wiphp\\Jump;\n\tpublic function _empty(){\n\t\t\$this->error(__MODULE__.'->'.__ACTION__.'() 不存在。');\n\t}\n}";
			file_put_contents(APP_PATH.'/controller/EmptyController.php', $p_empty);
			//基控制器
			$p_base = "<?php\nnamespace home\\controller;\nabstract class BaseController{\n\tuse \\wiphp\\Jump;\n\tpublic function __construct(){}\n}";
			file_put_contents(APP_PATH.'/controller/BaseController.php', $p_base);
			//演示extends基控制器
			$p_demo = "<?php\nnamespace home\\controller;\nclass DemoController extends BaseController{\n\tpublic function index(){\n\t\treturn 'Demo index!';\n\t}\n}";
			file_put_contents(APP_PATH.'/controller/DemoController.php', $p_demo);
			//演示路由配置
			$p_route = "<?php\nreturn [\n\t'/view/:id' => ['index/view', '*'],\n];";
			file_put_contents(APP_PATH.'/config/route.php', $p_route);
			
			unlink($lock);
		}
	}
}